package com.zrj.auth.core.extensions.mobile;

import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.AccountStatusException;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.token.AbstractTokenGranter;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 手机验证码授权者
 * @author zhaorujie
 */
public class SmsCodeTokenGranter extends AbstractTokenGranter {

    public static final String GRANT_TYPE = "sms_code";
    private final AuthenticationManager authenticationManager;

    public SmsCodeTokenGranter(AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService,
                               OAuth2RequestFactory auth2RequestFactory, AuthenticationManager authenticationManager) {
        super(tokenServices, clientDetailsService, auth2RequestFactory, GRANT_TYPE);
        this.authenticationManager = authenticationManager;
    }

    @Override
    protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
        Map<String, String> parameters = new LinkedHashMap<>(tokenRequest.getRequestParameters());
        //手机号
        String mobile = parameters.get("mobile");
        //验证码
        String code = parameters.get("code");

        parameters.remove(code);

        Authentication authentication = new SmsCodeAuthenticationToken(mobile, code);
        ((AbstractAuthenticationToken) authentication).setDetails(parameters);
        try {
            authentication = this.authenticationManager.authenticate(authentication);
        } catch (AccountStatusException | BadCredentialsException exception) {
            throw new InvalidGrantException(exception.getMessage());
        }
        if (authentication != null && authentication.isAuthenticated()) {
            OAuth2Request oAuth2Request = this.getRequestFactory().createOAuth2Request(client, tokenRequest);
            return new OAuth2Authentication(oAuth2Request, authentication);
        } else {
            throw new InvalidGrantException("Could not authenticate user: " + mobile);
        }
    }
}
